const personalKey = 'maix::personalKey::maix'
const jwt = require('jsonwebtoken')
const crypto = require('crypto');
const query = require('./query');
var sha256 = null;

//活着的用户token列表
let userTokenList = {
    /* username:token */
}

/**
 * 验证用户名和密码
 * @param {string} username 
 * @param {string} password 
 * @returns 
 */
async function verifyUser(username, password) {
    console.log(username, password);
    //TODO 从数据库匹配用户名和密码
    let userInfo = await query.getUser(username)
    if(userInfo && username === userInfo.id && password === userInfo.pwd) {
        //匹配到正确密码
        delete userInfo.pwd;
        return userInfo;
    }
    return null;

    // sha256 = crypto.createHash('sha256');
    // sha256.update('admin').digest("hex");
}

function sign(id) {
    let token = jwt.sign({
            id: String(id)
        },
        personalKey, {
            expiresIn: 3600 // 设置token的有效期 单位（秒）   
        }
    )
    if (!userTokenList[id]) {
        userTokenList[id] = token
    }
    return token
}

/**
 * token验证中间件
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
function verifyToken(req, res, next) {
    //console.log("verifyToken",req.body.token);
    //解析token
    let tokenData = jwt.verify(String(req.body.token), personalKey)
    //未登录
    if (!userTokenList[tokenData.id]) {
        throw new Error('Not logged in!');
    }
    let oldTokenData = jwt.verify(String(userTokenList[tokenData.id]), personalKey)
    console.log(tokenData, oldTokenData);
    if (tokenData.exp >= oldTokenData.exp)
        userTokenList[tokenData.id] = req.body.token;
    else{
        throw new Error('Token expired!');
    }
    next();
}

function checkTokenTimeout(token) {
    let tokenData = jwt.verify(String(token), personalKey)
    let nowTime = parseInt(new Date().getTime() / 1000)
    if (!userTokenList[tokenData.id]) {
        return {
            code: 1,
            msg: '未登录'
        }
    }
    // token有效期不到10分钟，则重新生成token
    if (tokenData.exp - nowTime < 360) {
        //刷新token
        token = sign(tokenData.id)
        return {
            code: 0,
            token
        }
    }
    return {
        code: 0,
        msg: 'token有效'
    }
}

function logout(token) {
    let tokenData = jwt.verify(String(token), personalKey)
    if (userTokenList[tokenData.id]) {
        userTokenList[tokenData.id] = "";
    } else {
        throw new Error('Not logged in!');
    }
}

module.exports = {
    verifyUser,
    sign,
    verifyToken,
    checkTokenTimeout,
    logout
};